package pub.cleangao.memm.transport.netty;


import lombok.extern.slf4j.Slf4j;
import pub.cleangao.memm.transport.message.RpcResponse;
import java.util.Map;
import java.util.concurrent.*;

@Slf4j
public class UnprocessedRequests {

    private UnprocessedRequests() {

    }

    private static UnprocessedRequests instance;

    public static synchronized UnprocessedRequests getInstance() {
        if (instance == null) {
            instance = new UnprocessedRequests();
        }
        return instance;
    }


    private static final Map<String, CompletableFuture<RpcResponse<Object>>> UNPROCESSED_RESPONSE_FUTURES = new ConcurrentHashMap<>();

    public void put(String requestId, CompletableFuture<RpcResponse<Object>> future) {
        UNPROCESSED_RESPONSE_FUTURES.put(requestId, future);
    }

    public void complete(RpcResponse<Object> rpcResponse) {
        CompletableFuture<RpcResponse<Object>> future = UNPROCESSED_RESPONSE_FUTURES.remove(rpcResponse.getRequestId());
        if (null != future) {
            future.complete(rpcResponse);
        } else {
            throw new IllegalStateException();
        }
    }
}
